package com.momo.hr.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.momo.hr.bean.RespBean;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义类SpringSecurity的过滤器类
 */
@Component
public class VerificationCodeFilter extends GenericFilter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //如果方法为POST方法 并且这个方法的资源路径是"/doLogin" 那么我们就去校验这个验证码
        if("POST".equals(req.getMethod()) && "/doLogin".equals(req.getServletPath())){
            //是登录页面那么我就把请求进行处理
            String code = req.getParameter("code");//获取校验码
            System.out.println(code);
            HttpSession session = req.getSession();
            String verify_code = (String)session.getAttribute("verify_code");//获取当前Session中的校验码
            System.out.println(verify_code);
            //获取请求路径的验证码出现了错误或者异常
            if(verify_code == null || verify_code == "" || !verify_code.toLowerCase().equals(code.toLowerCase()) ){
                //验证码不正确
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                writer.write(new ObjectMapper().writeValueAsString(RespBean.error("验证码错误")));
                writer.flush();
                writer.close();
            } else {
                //放过过滤器进行同行
                filterChain.doFilter(req,resp);

            }
        } else {
                //放过过滤器进行同行
                filterChain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}
